package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BaseException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private ShoppingPriceMaxService shoppingPriceMaxService;

    private final int TWO = 2;

    /**
     * 添加购物车模块
     * @param shoppingCartDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addCart(ShoppingCartDTO shoppingCartDTO) {
        //先判断当前要添加购物车的菜品是菜品还是套餐!!!
        if (shoppingCartDTO.getDishId() != null) {
            //先查询当前的菜品是否存在（避免前端缓存惹祸！）
            log.info("当前添加的是菜品");
            DishVO dishVO = dishMapper.getDishVOById(shoppingCartDTO.getDishId());
            if (dishVO == null || Objects.equals(dishVO.getStatus(), StatusConstant.DISABLE)) {
                log.info("当前添加的是'过期'的菜品！！正帮助您删除");
                //TODO这里还要删除[当前用户]购物车里面的（“过期”）的菜品
                //删除当前用户购物车里面的过期的菜品
                shoppingCartMapper.deleteShoppingCartByUserIdAndDishId(BaseContext.getCurrentId(), dishVO.getId());
                throw new BaseException(MessageConstant.DISH_ERROR);
            }
            log.info("开始判断购物车总值！");
            if(!shoppingPriceMaxService.AddPriceMAX(BaseContext.getCurrentId(), dishVO.getPrice())){
                throw new BaseException(MessageConstant.PRICE_MAX_ERROR);
            }
            log.info("检查状态通过！！");
            //若状态通过！就添加购物车查看购物车中是否有当前菜品！！
            ShoppingCart shoppingCart = shoppingCartMapper.getShoppingCartListByDishId(shoppingCartDTO.getDishId(), BaseContext.getCurrentId());
            if (shoppingCart == null) {
                log.info("购物车中没有此菜品的数据正在帮您添加菜品数据");
                //若为空就要添加当前新增的购物车菜品数据
                ShoppingCart newDish = ShoppingCart.builder()
                        .name(dishVO.getName())
                        .image(dishVO.getImage())
                        .userId(BaseContext.getCurrentId())
                        .dishId(dishVO.getId())
                        .dishFlavor(shoppingCartDTO.getDishFlavor())
                        .amount(dishVO.getPrice())
                        .createTime(LocalDateTime.now())
                        .build();
                shoppingCartMapper.insert(newDish);
                if (newDish.getId() == null) {
                    throw new BaseException(MessageConstant.INSERT_ERROR);
                }
            } else {
                log.info("购物车中已经有此菜品的数据正在帮您修改菜品数据");
                //不为空就代表查询的到！！购物车里面有这个菜品的数据！！！
                //现在就需要修改购物车里面的菜品的数据!!
                //先修改菜品的数量!!!
                log.info("处理当前的菜品的数量！{}", shoppingCart.getNumber());
                shoppingCart.setNumber(shoppingCart.getNumber() + 1);
                log.info("修改完成当前的菜品的数量！{}", shoppingCart.getNumber());
                //计算菜品的累加和!!!(重置当前的菜品的总金额)
                log.info("处理当前的菜品的金额！{}", shoppingCart.getAmount());
                //TODO 这里金额前端那边计算出错所以说就取消了
//                shoppingCart.setAmount(dishVO.getPrice().multiply(new BigDecimal(shoppingCart.getNumber())).setScale(TWO));
                shoppingCart.setAmount(dishVO.getPrice());
                log.info("修改完成当前的菜品的金额！{},调用Mapper层进行修改操作", shoppingCart.getAmount());
                int result = shoppingCartMapper.update(shoppingCart);
                if (result == StatusConstant.RETURN0) {
                    throw new BaseException(MessageConstant.UPDATE_FAILED);
                }
            }
        } else {
            log.info("当前添加的是套餐");
            //先查询当前的套餐是否存在（避免前端缓存惹祸！）
            SetmealVO setmealVO = setMealMapper.getSetMealById(shoppingCartDTO.getSetmealId());
            //判断当前套餐是否过期了！！
            if (setmealVO == null) {
                log.info("当前添加的是'过期'的套餐！！正帮助您删除");
                //TODO这里还要删除[当前用户]购物车里面的（“过期”）的套餐
                //删除当前用户购物车里面的过期的套餐
                shoppingCartMapper.deleteShoppingCartByUserIdAndSetMealId(BaseContext.getCurrentId(), setmealVO.getId());
                throw new BaseException(MessageConstant.SETMEAL_ERROR);
            }
            log.info("开始判断购物车总值！");
            if(!shoppingPriceMaxService.AddPriceMAX(BaseContext.getCurrentId(), setmealVO.getPrice())){
                throw new BaseException(MessageConstant.PRICE_MAX_ERROR);
            }
            log.info("检查状态通过！！");//若状态通过！就添加购物车查看购物车中是否有当前套餐！！
//            查看购物车中是否有当前的套餐！
            ShoppingCart shoppingCart = shoppingCartMapper.getShoppingCartListBySetMealId(BaseContext.getCurrentId(), setmealVO.getId());
            if (shoppingCart == null) {
                log.info("购物车中没有此套餐的数据正在帮您添加套餐数据");
                //若为空就要添加当前新增的购物车套餐数据
                ShoppingCart newSetMeal = ShoppingCart.builder()
                        .name(setmealVO.getName())
                        .image(setmealVO.getImage())
                        .userId(BaseContext.getCurrentId())
                        .setmealId(setmealVO.getId())
                        .amount(setmealVO.getPrice())
                        .createTime(LocalDateTime.now())
                        .build();
                shoppingCartMapper.insert(newSetMeal);
                if (newSetMeal.getId() == null) {
                    throw new BaseException(MessageConstant.INSERT_ERROR);
                }
            } else {
                log.info("购物车中已经有此套餐的数据正在帮您修改套餐数据");
                //不为空就代表查询的到！！购物车里面有这个套餐的数据！！！
                //现在就需要修改购物车里面的套餐的数据!!
                //先修改套餐的数量!!!
                log.info("处理当前的套餐的数量！{}", shoppingCart.getNumber());
                shoppingCart.setNumber(shoppingCart.getNumber() + 1);
                log.info("修改完成当前的套餐的数量！{}", shoppingCart.getNumber());
                //计算套餐的累加和!!!(重置当前的套餐的总金额)
                log.info("处理当前的套餐的金额！{}", shoppingCart.getAmount());
                //TODO 这里金额前端那边计算出错所以说就取消了
//                shoppingCart.setAmount(setmealVO.getPrice().multiply(new BigDecimal(shoppingCart.getNumber())).setScale(TWO));
                shoppingCart.setAmount(setmealVO.getPrice());
                log.info("修改完成当前的套餐的金额！{},调用Mapper层进行修改操作", shoppingCart.getAmount());
                int result = shoppingCartMapper.update(shoppingCart);
                if (result == StatusConstant.RETURN0) {
                    throw new BaseException(MessageConstant.UPDATE_FAILED);
                }
            }
        }
        //清除缓存
//        redisTemplate.delete(RedisDataBaseNameConstant.SHOPPING_CART_KEY + BaseContext.getCurrentId());
    }
    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> getShoppingCartList() {
        return shoppingCartMapper.getShoppingCartList(BaseContext.getCurrentId());
    }
    /**
     *删除一个购物车的商品
     * @param shoppingCartDTO
     * @return
     */
    @Override
    public void subCart(ShoppingCartDTO shoppingCartDTO) {
        if (shoppingCartDTO.getDishId() != null) {
            log.info("删除购物车菜品");
            ShoppingCart shoppingCartListByDishId = shoppingCartMapper.getShoppingCartListByDishId(shoppingCartDTO.getDishId(),BaseContext.getCurrentId() );
            if(shoppingCartListByDishId.getNumber()>1){
                shoppingCartListByDishId.setNumber(shoppingCartListByDishId.getNumber()-1);
                shoppingCartMapper.update(shoppingCartListByDishId);
            }else {
                shoppingCartMapper.deleteShoppingCartByUserIdAndDishId(BaseContext.getCurrentId(),shoppingCartDTO.getDishId());
            }
        }else {
            log.info("删除购物车套餐");
            ShoppingCart shoppingCartListBySetMealId = shoppingCartMapper.getShoppingCartListBySetMealId(BaseContext.getCurrentId(), shoppingCartDTO.getSetmealId());
            if(shoppingCartListBySetMealId.getNumber()>1){
                shoppingCartListBySetMealId.setNumber(shoppingCartListBySetMealId.getNumber()-1);
                shoppingCartMapper.update(shoppingCartListBySetMealId);
            }else {
                shoppingCartMapper.deleteShoppingCartByUserIdAndSetMealId(BaseContext.getCurrentId(),shoppingCartDTO.getSetmealId());
            }
        }
    }

    @Override
    public void cleanCart() {
        shoppingCartMapper.cleanCart(BaseContext.getCurrentId());
    }
}
